<?php
class Shepherd_UserController extends Sss_Controller_Shepherd
{
	public function init()
	{		
		parent::init();
	}
	/**
	* Login action - show the login form
	*/
	public function loginAction()
	{
		$this->checkInstance();
		$this->clearSession();
		$this->_helper->getHelper('layout')->disableLayout();

	}
	/**
	* Process for login action
	* @throws Sss_Exceptions_Abstract
	*/
	public function loginSubmitAction()
	{
		$handle =$this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
		$instanceTable  = new Application_Model_Mapper_Instance();
		$username = $this->getRequest()->getParam('username',"");
		$password = $this->getRequest()->getParam('password',"");
		$sessionStartLogin = new Zend_Session_Namespace(Sss_Ultility_SessionName::START_LOGIN_SESSION . $this->getCurrentHandle());
		$sessionStartLogin->startLogin  = Sss_Ultility_Setting::END_LOGIN;
		$this->checkInstance();
		$assignmentTable  = new Shepherd_Model_Mapper_Assignment();
		$permissionTable  = new Shepherd_Model_Mapper_Permission();
		$accountTable     = new Shepherd_Model_Mapper_Account();
		$accountOvisTable = new Application_Model_Mapper_Account();
		$instance = $instanceTable->getInstanceByHandle($handle);
		//Authentication with POST params
		$result = Sss_Controller_Shepherd_UserAdapter::checkLogin(array(
		'username' => $username,
		'password'=> $password
		), $instance->instanceid, $handle);
		if ($result) {
			//get user information by session when login
			$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());
			$roleId = $assignmentTable->getRoleByAccount($userInformation->accountid);//get role id by user id
			//get role list and assgin to session when check role will be get it
			$roleList = $permissionTable->getByRoleId($roleId->role);
			if($userInformation->username == Sss_Ultility_CommonViewParamater::USER_NAME_SHEPHERD_DEFAULT){
				$roleList = Sss_Ultility_Common::defaultListRoleAdministrator();
			}
			$sessionRoleList  = new Zend_Session_Namespace(Sss_Ultility_SessionName::ROLE_LIST_SESSION . $this->getCurrentHandle());
			$sessionRoleList->roleList = $roleList;
			//Create session with url auto login OTRS
			$sessionAutoLoginUrl = new Zend_Session_Namespace(Sss_Ultility_SessionName::SHEPHERD_AUTO_LOGIN_SESSION . $this->getCurrentHandle());
			$ot = new Sss_Ultility_OtrsServices();
			$encryptedPassword = Sss_Crypt::factory()->encrypt($password); //c2dfa7d5b0ff0b9046ab880e7e654df1
			$account = $accountTable->getUser($username);
			$accountTable->checkEsixtedColumns('otrs_user_id', $instance->instanceid);
			if (is_null($account->otrs_user_id)) {
				$arrParams = array();
				$arrParams['fullname'] =  $account->fullname;
				$arrParams['username'] =  $username . $account->accountid . $handle;
				$arrParams['password'] =  $encryptedPassword;
				$arrParams['email'] =  $account->accountid . $handle.$account->email;
				$arrParams['wsuser'] =  USER_SERVICE;
				$arrParams['wspass'] =  PASSWORD_SERVICE;
				$userOtrsId   = $ot->createCustomerUser(USER_SERVICE_ID, 1, $arrParams);
				if(!is_null($userOtrsId))
					$accountUpdate = $accountTable->findById($account->accountid,$instance->instanceid);
					$accountUpdate->setOtrsUserId($userOtrsId);
					$accountTable->save($accountUpdate,$instance->instanceid);
			} else { 
				Sss_Ultility_Common::logger()->log($username . $account->accountid . $handle . '-' . Resources::_('USER_NAME_EXIST'), Zend_Log::ALERT);
			}
			$crrInstances = $instanceTable->getConectedInstanceList($instance->instanceid);
			foreach($crrInstances as $inst){
				if(is_null($inst['otrs_group'])){
					$groupId = $ot->createGroup(USER_SERVICE_ID, 1, $handle, '', USER_SERVICE, PASSWORD_SERVICE);
					$ot->addQueue(USER_SERVICE_ID, 1, $handle, $groupId, USER_SERVICE, PASSWORD_SERVICE);
					// Update group id into table Instance
					$instanceUpdate = $instanceTable->findById($instance->instanceid);
					$instanceUpdate->setOtrsGroup($groupId);
					$instanceTable->updateData($instanceUpdate);
					// Call service of OTRS and update all ovis account to group when add new shepherd instance
					$ovisAccounts = $accountOvisTable->getAccountListByType(Sss_Ultility_Setting::ACCOUNT_OVIS);
					foreach($ovisAccounts as $ao){
						if(count($ovisAccounts) > 0){
							if(!is_null($ao['otrs_user_id']))
								$ot->assignUser2Group(USER_SERVICE_ID,$ao['otrs_user_id'], null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
						}
					}
					// Assign company owner of instance to OTRS group 
					$companyOwners = $accountOvisTable->getCompanyOwnerByStockLocation($inst['stocklocation']);
					if(count($companyOwners) > 0){
						foreach($companyOwners as  $companyOwner){
							if(!is_null($companyOwner['otrs_user_id'])){
								$otrs->assignUser2Group(USER_SERVICE_ID,$companyOwner['otrs_user_id'], null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
							}
						}
					}
				} else {
					$groupId = $inst['otrs_group'];
				}
				if(!is_null($groupId))
					$ot->assignCustomer2Group(USER_SERVICE_ID, $username . $account->accountid . $handle, null, $groupId, USER_SERVICE, PASSWORD_SERVICE);
			}
			$autoLogin =   $ot->autoLogin(USER_SERVICE_ID ,null,$username . $userInformation->accountid . $handle, $encryptedPassword, "Customer", USER_SERVICE, PASSWORD_SERVICE);
			$sessionAutoLoginUrl->autourl = $autoLogin;
			$this->_redirect("/$handle/");
		} else {
			if($username == "" || $password == "")
			{
				$this->view->message = Resources::_('INVALID_INPUT');
				$this->_forward(Sss_Ultility_CommonViewParamater::LOGIN);
			} else {
				$this->view->message = Resources::_('INVALID_USERNAME_PASSWORD');
				$this->_forward(Sss_Ultility_CommonViewParamater::LOGIN);
			}
		}
	}

	public function logoutAction() 
	{
		$this->clearSession();
		$handle =$this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
		$this->_redirect("/$handle/user/login");
	}
	public function forgotPasswordAction()
	{
		$this->_helper->getHelper('layout')->disableLayout();
	}
	public function forgotPasswordSubmitAction()
	{
		$instanceTable  = new Application_Model_Mapper_Instance();
		//get handle name
		$handle =$this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);

		$handleSession = new Zend_Session_Namespace(Sss_Ultility_SessionName::HANDLE_SESSION . $this->getCurrentHandle());

		$handleSession->handle = $handle;
		//get instance for check when not found
		$instance = $instanceTable->getInstanceByHandle($handle);
		$defaultNamespace = new Zend_Session_Namespace(Sss_Ultility_SessionName::SHEPHERD_SYSTEM . $this->getCurrentHandle());
		$defaultNamespace->dbShepherd = $instance->instanceid;
		$defaultNamespace->handle = $instance->handle;
		$defaultNamespace->stocklocationId = $instance->stocklocation;

		//get params
		$params = $this->getRequest()->getPost();

		if((!isset($params['username']) && !isset($params['email'])) || ($params['username'] == '' && $params['email'] == '')){
			$this->view->message = Resources::_('INVALID_INPUT');
			$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
			return;
		}
		//send mail to user with information active code
		$accountTable     = new Shepherd_Model_Mapper_Account();
		try {
			$email = null;
			if(isset($params['email']) && $params['email'] != ''){
				$account = $accountTable->getUserByEmail($params['email']);
				if($account != false){
					$email = $account->email;
				}
			}
			else if(isset($params['username']) && $params['username'] != ''){
					$account = $accountTable->getUser($params['username']);
					if($account != false){
						$email = $account->email;
					}
			}
			else{
				$this->view->message = Resources::_('INVALID_INPUT');
				$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
				return;
			}
			if($email == null){
				$this->view->message = Resources::_('INVALID_USERNAME_EMAIL');
				$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
				return; 
			}

			$getAccountId = $accountTable->getUserByEmail($email);
			$accountUpdate = $accountTable->findById($getAccountId->accountid,$instance->instanceid);
			$accountUpdate->setActivateCode($activateCode);
			$accountUpdate->setIsActivated(0);
			$accountTable->save($accountUpdate,$instance->instanceid);

			$handle =$this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
			$subject = Resources::_('SUBJECT_FORGOT_PASSWORD');

			$body    = Resources::_('BODY1'). " \n \n"
			.Resources::_('BODY2').' '.DOMAIN_SYSTEM."/$handle/active/active?activatecode=$activateCode&popup=1&forgotpassword=1". " \n \n"
			.Resources::_('BODY4'). " \n \n"
			.Resources::_('BODY5'). " \n \n"
			.Resources::_('BODY6');

			Sss_Ultility_Common::sendMail(EMAIL_SYSTEM, $email, $subject, $body);

			$this->view->message = Resources::_('RETRIEVE_PASSWORD_SUCCESSFULL');
			$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
		} catch (exception $e) {
			$this->view->message = Resources::_('RETRIEVE_PASSWORD_FAIL');
			$this->_forward(Sss_Ultility_CommonViewParamater::FORGOT_PASSWORD);
		}
	}
	public function changePasswordAction()
	{
		$this->checkInstance();
		$userInformation = new Zend_Session_Namespace(Sss_Ultility_SessionName::ACCOUNT_SESSION_SHEPHERD . $this->getCurrentHandle());

		$accountTable     = new Shepherd_Model_Mapper_Account();

		$handle =$this->getRequest()->getParam('handle', Sss_Ultility_CommonViewParamater::UNDERFINE);
		$this->view->assign('handle', $handle);
		$instanceTable = new Application_Model_Mapper_Instance();
		$instance = $instanceTable->getInstanceByHandle($handle);
		//get params
		$params = $this->getRequest()->getPost();

		if($userInformation->username && isset($params[Sss_Ultility_CommonViewParamater::BTN_SAVE])){
			//check username and password
			$account = $accountTable->getUser($userInformation->username);
			if($account != false)
				$account = (array)$account;
			$crypt = Sss_Crypt::factory();
			$encryptedPassword = $crypt->encrypt($params['currentpassword']);
			if($account != false && $encryptedPassword == $account['password']){
				//check confirm new password
				if(trim($params['password']) == trim($params['confirmnewpassword'])){
					try{
						$encryptedNewPassword = Sss_Crypt::factory()->encrypt($params['password']);
						$accountUpdate = $accountTable->findById($account['accountid'],$instance->instanceid);
						$accountUpdate->setPassword($encryptedNewPassword);
						$accountTable->save($accountUpdate);
						$this->view->message = Resources::_('CHANGE_PASSWORD_SUCCESSFULL');
						$this->_forward(Sss_Ultility_CommonViewParamater::LOGIN);
					} catch (exception $e) {
						$this->view->message = Resources::_('CHANGE_PASSWORD_FAIL');
						$this->_forward(Sss_Ultility_CommonViewParamater::CHANGE_PASSWORD);
					}
				} else {
					$this->view->message = Resources::_('CONFIRM_NEW_PASSWORD_FAIL');
					$this->_forward(Sss_Ultility_CommonViewParamater::CHANGE_PASSWORD);
				}
			}
		}
	}
}
